package com.tpvlog.dfs.datanode;

import com.tpvlog.dfs.datanode.file.ReplicateManager;
import com.tpvlog.dfs.datanode.file.StorageManager;
import com.tpvlog.dfs.datanode.resgiter.LeaseManager;
import com.tpvlog.dfs.datanode.server.DataNodeNIOServer;
import com.tpvlog.dfs.datanode.server.NameNodeRpcClient;

/**
 * DataNode启动类
 *
 * @author Ressmix
 */
public class DataNode {

    private volatile Boolean isRunning;

    // 与NameNode进行RPC通信的组件
    private NameNodeRpcClient rpcClient;

    // 负责文件存储管理的组件
    private StorageManager storageManager;

    // 负责副本复制的组件
    private ReplicateManager replicateManager;

    // 负责心跳和注册管理的组件
    private LeaseManager leaseManager;

    // 负责NIO通信的组件
    private DataNodeNIOServer nioServer;

    public static void main(String[] args) {
        DataNode datanode = new DataNode();
        datanode.initialize();
        datanode.start();
    }

    /**
     * 初始化DataNode
     */
    private void initialize() {
        this.rpcClient = new NameNodeRpcClient();
        this.storageManager = new StorageManager();
        this.replicateManager = new ReplicateManager(rpcClient);
        this.nioServer = new DataNodeNIOServer(rpcClient);
        this.leaseManager = new LeaseManager(rpcClient, storageManager, replicateManager);

        // 1.启动后立即进行一次注册
        leaseManager.register();
        // 2.开启心跳
        leaseManager.heartbeat();
        // 3.开启NIO Server
        nioServer.start();
    }

    /**
     * 运行DataNode
     */
    private void start() {
        this.isRunning = true;
        try {
            while (isRunning) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            this.isRunning = false;
            e.printStackTrace();
        }
    }
}
